<template>
  <div class="multi-cascader">
    <a-cascader
      v-model="selectedValue"
      ref="cascaderRef"
      allow-clear
      placeholder="请选择类型"
      :show-search="{ filter: handleCascaderSearch }"
      :options="processedOptions"
      :field-names="{ label: 'label', value: 'value', children: 'children' }"
      @change="handleAddSelection"
    />
    <div class="selected-tags">
      <a-tag v-for="(item, index) in selectedItems" :key="item.value" closable @close="handleRemoveSelection(index)">
        {{ item.label }}
      </a-tag>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import type { ShowSearchType } from 'ant-design-vue/lib/vc-cascader'

interface OptionNode {
  id: string
  value: string
  label: string
  way?: string // 明确声明way为可选属性
  children?: OptionNode[]
}

interface SelectedItem {
  id: string
  value: string
  label: string
  way?: string // 确保与OptionNode一致
  path: string[]
}

interface Props {
  industryList: OptionNode[]
  industryId?: string | string[]
}

interface Emits {
  (e: 'update:industryId', id: string[]): void
  (e: 'change', value: { ids: string[]; ways: (string | undefined)[] }): void // 修改emit类型
}

defineOptions({
  name: 'MultipleChoice'
})

const emit = defineEmits<Emits>()
const cascaderRef = ref()
const selectedValue = ref<string[]>([]) // 明确类型为string[]

const props = withDefaults(defineProps<Props>(), {
  industryList: () => []
})

const selectedItems = ref<SelectedItem[]>([])

// 处理选项数据，确保children为数组
const processedOptions = computed(() => {
  return props.industryList.map((item) => ({
    ...item,
    children: item.children || []
  }))
})

// 添加选择项
const handleAddSelection = (value: string[], selectedOptions: OptionNode[]) => {
  if (value.length === 0) return

  const lastOption = selectedOptions[selectedOptions.length - 1]

  // 检查是否已存在相同value的选项
  const exists = selectedItems.value.some((item) => item.value === lastOption.value)
  if (!exists) {
    selectedItems.value.push({
      id: lastOption.id,
      value: lastOption.value,
      label: lastOption.label,
      way: lastOption.way, // 确保way被正确传递
      path: selectedOptions.map((opt) => opt.label)
    })
    updateModel()
  }

  selectedValue.value = [] // 清空选择器
}

// 移除选择项
const handleRemoveSelection = (index: number) => {
  selectedItems.value.splice(index, 1)
  updateModel()
}

// 更新模型值
const updateModel = () => {
  const selectedIds = selectedItems.value.map((item) => item.id)
  const selectedWays = selectedItems.value.map((item) => item.way) // 获取所有way值
  console.log(selectedWays, 'selectedWays', selectedItems.value)

  emit('update:industryId', selectedIds)
  emit('change', {
    ids: selectedIds,
    ways: selectedWays // 将ways一并emit出去
  })
}

// 暴露selectedItems给父组件
defineExpose({
  selectedItems
})

// 搜索过滤
const handleCascaderSearch: ShowSearchType['filter'] = (inputValue, path) => {
  return path.some((option) => option.label.toLowerCase().includes(inputValue.toLowerCase()))
}
</script>
